package com.cn.cxq.util;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cn.cxq.bean.BasicBean;

public class SQLUtil extends BasicBean {
	public static Timestamp getTime(Connection con) throws SQLException {
		Timestamp ts = null;
		String SQL = "SELECT NOW() AS curTime";

		Statement stmt = con.createStatement();
		ResultSet rs = stmt.executeQuery(SQL);

		if (rs.next()) {
			ts = rs.getTimestamp(1);
		}
		rs.close();
		stmt.close();
		if (ts == null) {
			throw new SQLException("Failed to get current time.");
		}
		return ts;
	}

	public static void cleanUp(ResultSet rs, PreparedStatement pst) {
		try {
			if (rs != null)
				rs.close();
			if (pst != null)
				pst.close();
		} catch (SQLException e) {
			throw new RuntimeException(e.getMessage());
		}
	}
	
	public static Object getObj(ResultSet rs) {
		return rs;
	}
	
	public static List<Object> getObjList(ResultSet rs) {
		try {
			while (rs.next()) {
				Object obj = new Object();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static DynamicDataSource getDynamicDataSource(HttpServletRequest request){
		ServletContext  sc = request.getSession().getServletContext();
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sc);
		return (DynamicDataSource)wac.getBean("dynamicDataSource");
	}
	
	public static Connection getConnection(HttpServletRequest request, String sqlSource) throws SQLException {
		CustomerContextHolder.setCustomerType(sqlSource); 
		DynamicDataSource dataSource = getDynamicDataSource(request);
		return dataSource.getConnection();
	}
}
